﻿namespace DimensionsHelper.Client.WinUi.Services;

public sealed partial class ProjectTaskService : ObservableObject, IProjectTaskService
{
    private readonly ObservableCollection<IProjectTask> _tasks = [];


    [ObservableProperty]
    public partial IProjectTask? Current
    {
        get;
        set;
    }


    public IEnumerable<IProjectTask> Tasks => _tasks;


    public IProjectTask Allocate(string section, bool canRemove = true)
    {
        string id = section;
        int count = 1;

        while (Tasks.FirstOrDefault(task => task.Id == id) is { } cachedTask)
        {
            if (!cachedTask.IsRunning)
            {
                return Current = cachedTask;
            }

            id = $"{section}`{count}";
            count++;
        }

        Current = new ProjectTask { Id = id, Section = section, CanRemove = canRemove };
        _tasks.Add(Current);
        return Current;
    }


    public void Remove(IProjectTask task)
    {
        if (task is ProjectTask projectTask)
        {
            _tasks.Remove(projectTask);
        }
    }
}